package com.anrongtec.zcpt.tab02;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseFragment;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.module.PageList;
import com.anrongtec.zcpt.listener.AppBarStateChangeListener;
import com.anrongtec.zcpt.manager.APPDownloadManager;
import com.anrongtec.zcpt.manager.AppDownManagerActivity;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.module.Type;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.LogUtil;
import com.anrongtec.zcpt.util.SnackbarUtil;
import com.anrongtec.zcpt.util.Util;
import com.anrongtec.zcpt.view.FloatSearchView;
import com.anrongtec.zcpt.view.LoadingView;
import com.anrongtec.zcpt.view.SearchTagView;
import com.anrongtec.zcpt.view.SearchTagView.onSeclctListener;
import com.art.base.util.ApkUtils;
import com.art.base.util.DialogUtil;
import com.art.base.util.FileUtils;
import com.art.base.util.NetUtil;
import com.art.base.util.ToastShow;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter.OnItemClickListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import deadline.swiperecyclerview.SwipeRecyclerView;
import deadline.swiperecyclerview.SwipeRecyclerView.OnLoadListener;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class TabSecondNewFragment extends BaseFragment implements OnItemClickListener {
    // private VerticalSwipeRefreshLayout swipe_refresh;
    private View view;
    /**
     * 加载页面
     */
    private View loading;
    // private LinearLayout ll_loading;
    private TextView tv_loading;
    private ProgressBar pb_loading;
    /**
     * 消失动画
     */
    private Animation out;
    private AppBarLayout appbarLayout;
    private SearchTagView stv_tab02;
    private CollapsingToolbarLayout ctl_tab_second_new;
    private List<List<Type>> mTagList;
    private SwipeRecyclerView rv_tab02_new;
    private CommonAdapter<AppModel> adapter;
    private EmptyWrapper<AppModel> emptyWrapper;
    private LoadingView loadingView;
    private List<AppModel> mAppList;
    // 滑动浮动搜索View
    private FloatSearchView ll_float_search_view;
    private ProgressDialog progressDialog;
    // recycleView 下拉刷新页数
    private int page = 1;
    // 搜索条件
    private List<Type> mSearchTermsList;
    private String str_search_terms;
    private StringBuilder sb_search_terms;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_tab_second_new, null);
        initViews(view);
        initData();
        return view;
    }

    @Override
    protected void initViews(View view) {
        ctl_tab_second_new = (CollapsingToolbarLayout) view.findViewById(R.id.ctl_tab_second_new);
        initLoading(view);
        initAppBarLayout(view);
        initSearchTagView(view);
        initRecycle(view);
        initFloatSearchView(view);
    }

    /**
     * 加载悬浮搜索框
     */
    private void initFloatSearchView(View view) {
        ll_float_search_view = new FloatSearchView(getContext());
        // ll_float_search_view.setSearchTagView(stv_tab02);
        // rv_tab02_new.addView(ll_float_search_view);
        // ll_float_search_view.setTagList(mTagList);
    }

    /**
     * 加载列表
     */
    private void initRecycle(View view) {
        rv_tab02_new = (SwipeRecyclerView) view.findViewById(R.id.rv_tab02_new);
        rv_tab02_new.getRecyclerView().setLayoutManager(new LinearLayoutManager(getContext()));
        // rv_tab02_new.setEmptyView(loading);
        rv_tab02_new.setLoadMoreEnable(true);
        mAppList = new ArrayList<AppModel>();
        adapter = new CommonAdapter<AppModel>(getContext(), R.layout.item_app, mAppList) {
            @Override
            protected void convert(ViewHolder holder, AppModel t, final int position) {
                final AppModel app = mAppList.get(position);
                ImageView iv = holder.getView(R.id.iv_item_app_icon);
                ImageLoader.getInstance().displayImage(app.getIconUrl(), iv);
                holder.setText(R.id.tv_item_app_name, app.getAppName());
                holder.setRating(R.id.ratingbar_item_app_score, app.getScore());
                holder.setText(R.id.tv_item_app_total_size, Util.byte2Mega(app.getSize()));
                holder.setText(R.id.tv_item_app_version_name, app.getRemoteVersionName());

                final DownloadInfo downloadInfo = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
                if (downloadInfo != null && downloadInfo.getState() == DownloadManager.FINISH) {
                    if (ApkUtils.isNeedOpen(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "打开");
                    } else if (ApkUtils.isNeedUpdate(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "更新");
                    } else {
                        if (FileUtils.isExist(downloadInfo.getTargetPath())) {
                            holder.setText(R.id.btn_item_app_install, "安装");
                        } else {
                            holder.setText(R.id.btn_item_app_install, "下载");
                        }
                    }
                } else if (downloadInfo != null && downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                    holder.setText(R.id.btn_item_app_install, "正在下载");
                } else {
                    if (ApkUtils.isNeedOpen(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "打开");
                    } else if (ApkUtils.isNeedUpdate(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "更新");
                    } else {
                        holder.setText(R.id.btn_item_app_install, "下载");
                    }
                }


                final View button = holder.getView(R.id.btn_item_app_install);

                holder.setOnClickListener(R.id.btn_item_app_install, new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DownloadInfo info = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
                        // 如果该任务的状态为完成
                        if (info != null && info.getState() == DownloadManager.FINISH) {
                            // 如果已经安装则打开; 未安装,判断安装包是否存在. 如果存在则安装, 不存在则重新下载;
                            // if (ApkUtils.isAvailable(getContext(),
                            // app.getAppPackName())) {
                            if (ApkUtils.isNeedOpen(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
                                if (app.getActivity() == null||app.getActivity().equals("")) {//有图标的打开方式
                                    ApkUtils.openAPP(getContext(), app.getAppPackName());
                                }
                                else {//无图标打开方式
                                    //ApkUtils.openDefaultApp(getActivity(),app.getAppPackName());
                                    ApkUtils.openAPP(getContext(), app.getAppPackName(), app.getActivity());
                                }
                            } else {
                                if (FileUtils.isExist(info.getTargetPath())) {
                                    // TODO 安装
                                    ApkUtils.installSilent(getActivity(), new File(info.getTargetPath()));
//                                    ApkUtils.install(getActivity(), new File(info.getTargetPath()));
                                } else {
                                    APPDownloadManager.removeTask(info.getTaskKey());
                                    APPDownloadManager.addTask(getActivity(), app, info.getListener());
                                    // TODO 点击下载后跳转到下载列表页面吗?
                                    // startActivity(AppDownManagerActivity.class);
                                    SnackbarUtil.showSnackbar(getActivity(), button);
                                    emptyWrapper.notifyItemChanged(position);
                                }
                            }
                        } else if (info != null && info.getState() == DownloadManager.DOWNLOADING) {
                            intent = new Intent(getActivity(), AppDownManagerActivity.class);
                            startActivity(intent);
                        } else {
                            if (ApkUtils.isNeedOpen(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
                                if (app.getActivity() == null||app.getActivity().equals("")) {//有图标的打开方式
                                    ApkUtils.openAPP(getContext(), app.getAppPackName());
                                } else {//无图标打开方式
                                    //ApkUtils.openDefaultApp(getActivity(),app.getAppPackName());
                                    ApkUtils.openAPP(getContext(), app.getAppPackName(), app.getActivity());
                                }
                            } else {
                                APPDownloadManager.addTask(getActivity(), app, null);
                                // TODO 点击下载后跳转到下载列表页面吗?
                                // startActivity(AppDownManagerActivity.class);
                                SnackbarUtil.showSnackbar(getActivity(), button);
                                emptyWrapper.notifyItemChanged(position);
                            }
                        }
                    }

                });
            }
        };
        adapter.setOnItemClickListener(this);
        emptyWrapper = new EmptyWrapper<>(adapter);
        loadingView = new LoadingView(getContext());
        loadingView.setStatue(LoadingView.LOADING);
        // loadingView 此时并没有绘制测量，造成显示错误，所以需要重新复制
        LayoutParams lp = (LayoutParams) loadingView.getLayoutParams();
        if (lp == null) {
            lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }
        lp.width = LayoutParams.MATCH_PARENT;
        lp.height = LayoutParams.MATCH_PARENT;
        loadingView.setLayoutParams(lp);
        emptyWrapper.setEmptyView(loadingView);
        loadingView.setVisibility(View.GONE);
        rv_tab02_new.setAdapter(emptyWrapper);
        rv_tab02_new.setOnLoadListener(new OnLoadListener() {

            @Override
            public void onRefresh() {
                initAppInfo(true);
            }

            @Override
            public void onLoadMore() {
                initAppInfo(false);

            }
        });
        // 设置自动下拉刷新，切记要在recyclerView.setOnLoadListener()之后调用
        // 因为在没有设置监听接口的情况下，setRefreshing(true),调用不到OnLoadListener
    }

    @Override
    protected void initData() {
        initTag();
    }

    private void initTag() {
        String json = GsonUtil.toTypeQueryJson();
        HttpUtil.post(json, new StoreStringCallBack(getActivity()) {
            @Override
            public void onResponse(boolean arg0, String json, Request arg2, Response arg3) {
                super.onResponse(arg0, json, arg2, arg3);
                JsonDataRestult<Map<String, List<List<Type>>>> result = GsonUtil.decode(json,
                        new TypeToken<JsonDataRestult<Map<String, List<List<Type>>>>>() {
                        }.getType());
                LogUtil.e(json);
                if (result == null) {
                    pb_loading.setVisibility(View.GONE);
                    tv_loading.setText("点击重新加载...");
                    ToastShow.shortMessage("数据加载失败...");
                    return;
                }
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    Map<String, List<List<Type>>> m = result.getData();
                    mTagList = m.get("type");
                    stv_tab02.setSourceData(mTagList);
                    disappearLoading();
                } else {
                    ToastShow.shortMessage(result.getRetMsg());
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                super.onError(isFromCache, call, response, e);
                pb_loading.setVisibility(View.GONE);
                tv_loading.setText("点击重新加载...");
            }

        });
    }

    /**
     * 初始化加载页面
     *
     * @param view
     */
    private void initLoading(View view) {
        loading = view.findViewById(R.id.loading);
        tv_loading = (TextView) view.findViewById(R.id.tv_loading);
        pb_loading = (ProgressBar) loading.findViewById(R.id.pb_loading);
        tv_loading.setText("正在加载中...");
        out = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out);
        // ll_loading = (LinearLayout) loading.findViewById(R.id.ll_loading);
        loading.setClickable(false);
        loading.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                initTag();
                pb_loading.setVisibility(View.VISIBLE);
                tv_loading.setText("正在重新加载...");
            }
        });
    }

    /**
     * 加载页面消失 @Title: disappearLoading @Description:
     * TODO(这里用一句话描述这个方法的作用) @param 设定文件 @return void 返回类型 @throws
     */
    private void disappearLoading() {
        loading.setAnimation(out);
        loading.setVisibility(View.GONE);
    }

    /**
     * 初始化appbarlayout
     */
    private void initAppBarLayout(final View view) {
        appbarLayout = (AppBarLayout) view.findViewById(R.id.appbarlayout_tab02_new);
        appbarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    // TODO 禁用下拉刷新 展开状态
                    rv_tab02_new.setRefreshEnable(true);
                    // ll_float_search_view.setVisibility(View.GONE);
                } else if (state == State.COLLAPSED) {
                    // 折叠状态
                    rv_tab02_new.setRefreshEnable(false);
                    // ll_float_search_view.showUnexpandSearchView(sb_search_terms.toString());
                } else {
                    // 中间状态\
                    rv_tab02_new.setRefreshEnable(false);
                    // ll_float_search_view.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initSearchTagView(View view) {
        mSearchTermsList = new ArrayList<>();
        stv_tab02 = (SearchTagView) view.findViewById(R.id.stv_tab02);
        stv_tab02.setOnselectListener(new onSeclctListener() {

            @Override
            public void onSelect(List<Type> mTypes) {
                loadingAppInfo();
                ctl_tab_second_new.scrollBy(0, 0);
                sb_search_terms = new StringBuilder();
                if (mTypes.isEmpty()) {
                    return;
                }
                for (Type type : mTypes) {
                    sb_search_terms.append(type.getName()).append("·");
                }
                sb_search_terms.deleteCharAt(sb_search_terms.length() - 1);
            }
        });
        // stv_tab02 = new SearchTagView(getContext());
        // ctl_tab_second_new.addView(stv_tab02);
    }

    /**
     * 获取App信息
     */
    private void initAppInfo(final boolean isRefresh) {
        // 先判断是否有网络
        if (!NetUtil.isNetworkAvailable(getContext().getApplicationContext())) {
            ToastShow.shortMessage("暂无网络连接,请稍后再试");
            mAppList.clear();
            loadingView.setStatue(LoadingView.NO_NETWORK);
            rv_tab02_new.complete();
            rv_tab02_new.stopLoadingMore();
            rv_tab02_new.onNoMore("-- 暂无网络 --");
            emptyWrapper.notifyDataSetChanged();
            return;
        }
        if (isRefresh) {
            page = 1;
        } else {
            page++;
        }
        String json = GsonUtil.toQueryAppJson("", stv_tab02.getSearchList(), page);
        LogUtil.e("商店内容请求体 = " + json);
        HttpUtil.post(json, new StoreStringCallBack(getActivity()) {
            @Override
            public void onResponse(boolean arg0, String json, Request arg2, Response arg3) {
                super.onResponse(arg0, json, arg2, arg3);
                LogUtil.e("商店内容返回 = " + json);
                JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(json,
                        new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
                        }.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    if (isRefresh) {
                        mAppList.clear();
                        mAppList.addAll(result.getData().getApps());
                        rv_tab02_new.complete();
                    } else {
                        mAppList.addAll(result.getData().getApps());
                        rv_tab02_new.stopLoadingMore();
                        LogUtil.e("stopLoadingMore = ");
                    }
                    if (result.getData().getApps().size() < 10) {
                        rv_tab02_new.stopLoadingMore();
                        rv_tab02_new.onNoMore("-- 共" + mAppList.size() + "款应用 --");
                        LogUtil.e("stopLoadingMore = " + mAppList.size());
                    }
                    if (mAppList.size() == 0) {
                        LogUtil.e("size() == 0 " + mAppList.size());
                        loadingView.setStatue(LoadingView.NO_DATA);
                        ToastShow.shortMessage("没有该类应用");
                    }
                    emptyWrapper.notifyDataSetChanged();
                } else {
                    rv_tab02_new.complete();
                    ToastShow.shortMessage(result.getRetMsg());
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                super.onError(isFromCache, call, response, e);
                LogUtil.e("onError() == 0 ");
            }

        });
    }

    /**
     * 点击查询条件时候加载App信息
     */
    private void loadingAppInfo() {
        // 先判断是否有网络
        if (!NetUtil.isNetworkAvailable(getContext().getApplicationContext())) {
            ToastShow.shortMessage("暂无网络连接,请稍后再试");
            rv_tab02_new.stopLoadingMore();
            rv_tab02_new.onNoMore("-- 暂无网络 --");
            emptyWrapper.notifyDataSetChanged();
            return;
        }
        if (progressDialog == null) {
            progressDialog = DialogUtil.createLoadingDialog(getContext(), "正在加载应用列表...");
        }
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        page = 1;
        String json = GsonUtil.toQueryAppJson("", stv_tab02.getSearchList(), page);
        HttpUtil.post(json, new StoreStringCallBack(getActivity()) {
            @Override
            public void onResponse(boolean arg0, String json, Request arg2, Response arg3) {
                super.onResponse(arg0, json, arg2, arg3);
                JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(json,
                        new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
                        }.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    mAppList.clear();
                    mAppList.addAll(result.getData().getApps());
                    rv_tab02_new.stopLoadingMore();
                    if (result.getData().getApps().size() < 10) {
                        rv_tab02_new.stopLoadingMore();
                        rv_tab02_new.onNoMore("-- 共" + mAppList.size() + "款应用 --");
                    }
                    if (mAppList.size() == 0) {
                        loadingView.setStatue(LoadingView.NO_DATA);
                    }
                    emptyWrapper.notifyDataSetChanged();

                } else {
                    rv_tab02_new.stopLoadingMore();
                    ToastShow.shortMessage(result.getRetMsg());
                }
                if (null != progressDialog && progressDialog.isShowing()) {
                    progressDialog.cancel();
                }

            }

            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                super.onError(isFromCache, call, response, e);
                ToastShow.shortMessage("加载数据错误...");
                if (null != progressDialog && progressDialog.isShowing()) {
                    progressDialog.cancel();
                }
            }

        });
    }

    /**
     * 更新
     */
    public void refresh() {
        if (emptyWrapper != null) {
            emptyWrapper.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(View view, android.support.v7.widget.RecyclerView.ViewHolder holder, int position) {
        intent = new Intent(getActivity(), AppDetailActivity.class);
        AppModel app = mAppList.get(position);
        intent.putExtra(Constant.DATA, app);
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(View view, android.support.v7.widget.RecyclerView.ViewHolder holder, int position) {
        return false;
    }

}
